const express = require('express');
const multer = require('multer');
const { PDFDocument } = require('pdf-lib');
const cors = require('cors');
const fs = require('fs');
const path = require('path');
const { spawn } = require('child_process');

const app = express();
const upload = multer({ dest: 'uploads/' });
app.use(cors());
app.use(express.json());

// PDF合并
app.post('/api/pdf/merge', upload.array('pdfs'), async (req, res) => {
  try {
    const mergedPdf = await PDFDocument.create();
    for (const file of req.files) {
      const pdfBytes = fs.readFileSync(file.path);
      const pdf = await PDFDocument.load(pdfBytes);
      const copiedPages = await mergedPdf.copyPages(pdf, pdf.getPageIndices());
      copiedPages.forEach((page) => mergedPdf.addPage(page));
      fs.unlinkSync(file.path);
    }
    const mergedBytes = await mergedPdf.save();
    res.setHeader('Content-Type', 'application/pdf');
    res.setHeader('Content-Disposition', 'attachment; filename=merged.pdf');
    res.send(Buffer.from(mergedBytes));
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// PDF拆分（每页单独导出）
app.post('/api/pdf/split', upload.single('pdf'), async (req, res) => {
  try {
    const pdfBytes = fs.readFileSync(req.file.path);
    const pdf = await PDFDocument.load(pdfBytes);
    const pageBuffers = [];
    for (let i = 0; i < pdf.getPageCount(); i++) {
      const newPdf = await PDFDocument.create();
      const [copiedPage] = await newPdf.copyPages(pdf, [i]);
      newPdf.addPage(copiedPage);
      const bytes = await newPdf.save();
      pageBuffers.push(bytes);
    }
    fs.unlinkSync(req.file.path);
    res.json({
      pages: pageBuffers.map((buf, idx) => {
        const base64 = Buffer.from(buf).toString('base64');
        return { filename: `page_${idx + 1}.pdf`, base64 };
      })
    });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// PDF加密（使用PyPDF2）
app.post('/api/pdf/encrypt', upload.single('pdf'), async (req, res) => {
  try {
    const { password } = req.body;
    const inputPath = req.file.path;
    const outputPath = inputPath + '_enc.pdf';
    // 调用python脚本加密
    const py = spawn('python', [
      path.join(__dirname, 'pdf_encrypt.py'),
      inputPath,
      outputPath,
      password
    ]);
    py.on('close', (code) => {
      if (code === 0 && fs.existsSync(outputPath)) {
        const encryptedBytes = fs.readFileSync(outputPath);
        fs.unlinkSync(inputPath);
        fs.unlinkSync(outputPath);
        res.setHeader('Content-Type', 'application/pdf');
        res.setHeader('Content-Disposition', 'attachment; filename=encrypted.pdf');
        res.send(Buffer.from(encryptedBytes));
      } else {
        fs.unlinkSync(inputPath);
        if (fs.existsSync(outputPath)) fs.unlinkSync(outputPath);
        res.status(500).json({ error: 'PDF加密失败，请检查文件格式或密码。' });
      }
    });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// PDF解密（使用PyPDF2）
app.post('/api/pdf/decrypt', upload.single('pdf'), async (req, res) => {
  try {
    const { password } = req.body;
    const inputPath = req.file.path;
    const outputPath = inputPath + '_dec.pdf';
    // 调用python脚本解密
    const py = spawn('python', [
      path.join(__dirname, 'pdf_decrypt.py'),
      inputPath,
      outputPath,
      password
    ]);
    py.on('close', (code) => {
      if (code === 0 && fs.existsSync(outputPath)) {
        const decryptedBytes = fs.readFileSync(outputPath);
        fs.unlinkSync(inputPath);
        fs.unlinkSync(outputPath);
        res.setHeader('Content-Type', 'application/pdf');
        res.setHeader('Content-Disposition', 'attachment; filename=decrypted.pdf');
        res.send(Buffer.from(decryptedBytes));
      } else {
        fs.unlinkSync(inputPath);
        if (fs.existsSync(outputPath)) fs.unlinkSync(outputPath);
        res.status(500).json({ error: 'PDF解密失败，请检查文件或密码。' });
      }
    });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

const PORT = 5001;
app.listen(PORT, () => {
  console.log(`PDF处理服务已启动，端口：${PORT}`);
}); 